'use strict';
module.exports = {
	/**
	 * 公众号推送入口
	 * @url client/mp/pub/index 前端调用的url参数地址
	 * data 请求参数
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, originalParam
		} = event;
		let {
			customUtil,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		let {
			uid
		} = data;
		let res = {
			code: 0,
			msg: "",
		};
		// 业务逻辑开始-----------------------------------------------------------
		// 所有的逻辑都在这里写
		// 比如上边写到的
		const {
			name,
			time,
			address,
			url
		} = data
		const dataSource = {
			thing1: {
				value: name
			},
			time2: {
				value: time
			},
			thing3: {
				value: address
			},
		}

		// 获取token
		let timestamp = new Date().getTime(); // uniCloud中尽量使用毫秒时间戳
		let accessToken;
		let oldAccessToken = await vk.baseDao.selects({
			dbName: "wx-mp-cache",
			getOne: true,
			getMain: true,
			whereJson: {
				name: 'accessToken'
			},
			sortArr: [{
				name: 'expire_time',
				type: 'desc'
			}]
		});
		if (vk.pubfn.isNotNull(oldAccessToken) && oldAccessToken.expire_time > timestamp) {
			accessToken = oldAccessToken.token
		} else {
			let accessTokenRes = await uniCloud.httpProxyForEip.get('https://api.weixin.qq.com/cgi-bin/token', {
				grant_type: 'client_credential',
				appid: 'wx6954444f473c9626', // 换成你自己的
				secret: '3f5f375fb5c147818697b80cc23f7328' // 换成你自己的
			});
			let newExpireTime = parseInt(timestamp) + 7200000
			await vk.baseDao.add({
				dbName: "wx-mp-cache",
				dataJson: {
					name: 'accessToken',
					token: accessTokenRes.body.access_token, // 注意看这里，代理请求的结果，数据是在body中……
					expire_time: newExpireTime // 2小时过期
				}
			});
			accessToken = accessTokenRes.body.access_token
		}

		// 获取每一个有openid的用户信息
		let userList = await vk.baseDao.selects({
			dbName: "uni-id-users",
			getMain: true,
			whereJson: {
				wx_openid: _.exists(true),
			},
		});
		for (let i = 0; i < userList.length; i++) {
			let result = await uniCloud.httpclient.request(
				'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' +
				accessToken, {
					method: 'POST',
					dataType: 'json',
					data: JSON.stringify({
						touser: userList[i].wx_openid.h5,
						template_id: 'up67-Zs8UwnXLzaqoQqoc-mJixLS8SxtR7gXFYNdh74',
						url,
						data: dataSource
					}),
				});
			console.log(result)
		}
		res.msg = '直播通知成功'
		res.code = 0
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}